package com.gmall.rabbitmq.producer.service;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class ReliableRabbitMQService {


    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void  init(){
        System.out.println("初始化时执行");

        //Confirm 当交换机收到消息后是否返回确认信息
        /*
         * 开启后，一定会收到
         * 1. 交换机收到消息，返回确认信息 ack = true
         * 2. 交换机没有收到消息，返回错误信息 ack = false
         */
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData,
                                           boolean ack,
                                           String cause)->{
            System.out.println(correlationData);
            System.out.println("ack = " + ack);
            System.out.println("cause = "+ cause);
            if(ack){
                System.out.println("消息发送到交换机成功");
            }else{
                System.out.println("消息发送到交换机失败");
            }
        });

        /*
         * 1. 如果路由不到队列,会调用下面的方法
         */
        rabbitTemplate.setReturnCallback((Message message,
                                          int replyCode,
                                          String replyText,
                                          String exchange,
                                          String routingKey)->{
            System.out.println("message = " + message);
            System.out.println("replyCode = " + replyCode);
            System.out.println("replyText = " + replyText);
            System.out.println("exchange = " + exchange);
            System.out.println("routingKey = " + routingKey);
            //replyCode = 312,replyText = NO_ROUTE
            //记录日志
        });
    }
}
